package com.bridgeintelligent.tag.customer.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.bridgeintelligent.tag.constants.ExceptionCodes;
import com.bridgeintelligent.tag.constants.Permissions;
import com.bridgeintelligent.tag.constants.TagConstants;
import com.bridgeintelligent.tag.constants.bulkload.FileLoadMqMsg;
import com.bridgeintelligent.tag.constants.bulkload.MQConfig;
import com.bridgeintelligent.tag.constants.bulkload.StaticMqMsg;
import com.bridgeintelligent.tag.customer.constant.PublicConstant;
import com.bridgeintelligent.tag.customer.entity.CustomersPage;
import com.bridgeintelligent.tag.customer.entity.OcdsmDownLog;
import com.bridgeintelligent.tag.customer.entity.Result;
import com.bridgeintelligent.tag.customer.ess.EssQueryModel;
import com.bridgeintelligent.tag.customer.ess.EssResult;
import com.bridgeintelligent.tag.customer.mapper.ApplyInfoMapper;
import com.bridgeintelligent.tag.customer.mapper.CustomersMapper;
import com.bridgeintelligent.tag.customer.mapper.RecordMapper;
import com.bridgeintelligent.tag.customer.ocdsm.OcdsmModel;
import com.bridgeintelligent.tag.customer.ocdsm.OcdsmService;
import com.bridgeintelligent.tag.customer.pojo.*;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.utils.FieldHandler;
import com.bridgeintelligent.tag.utils.SecurityHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.bridgeintelligent.tag.webserver.workflow.*;
import com.bridgeintelligent.tag.webserver.workflow.repository.InstanceMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ocdsm.ResultObject;
import com.wayneleo.quickstart.QuickException;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.bridgeintelligent.tag.customer.exception.CustomerErrors.ERROR_401006;

/**
 * 客群审批服务层实现
 */
@Service
@AllArgsConstructor
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class CustomerApprovalService implements ICustomerApprovalService {

    private SubmitterService submitterService;
    private ApproverService approverService;
    private CustomersMapper customersMapper;
    private InstanceMapper instanceMapper;
    private RocketMQTemplate rocketMQTemplate;
    private ObjectMapper objectMapper;
    private RecordMapper recordMapper;
    private CustomersService customersService;

    private ApplyInfoMapper applyInfoMapper;

    private OcdsmService ocdsmService;

    private EssApproveServiceImpl essApproveService;

    @Override
    public String addCommit(String customerId, ExportSet exportSet) {
        Instance instance = submitterService.submit(new SubmitterService.SubmitParam().setResourceId(customerId)
                                                                                      .setWorkflowId(TagConstants.Workflow.ID_10008));
        User user = TagSecurityHelper.currentUser();
        exportSet.setUserId(user.getUserId());
        exportSet.setUserName(user.getName());
        exportSet.setInstanceId(instance.getId());
        exportSet.setIsready("0");
        exportSet.setCreateTime(DateHelper.currentDateTime());
        exportSet.setUptTime(DateHelper.currentDateTime());
        addExportSet(exportSet);
        return instance.getId();
    }

    @Override
    public Result addCCISCommit(ExportSet exportSet) {
        if(Objects.isNull(exportSet.getApplyInfo())){
            return new Result(-1, "敏感数据导出,缺失相关申请信息！");
        }
        User user = TagSecurityHelper.currentUser();
        exportSet.setId(IDGenerator.gen());
        exportSet.setUserId(user.getUserId());
        exportSet.setUserName(user.getName());
        exportSet.setIsready("0");
        exportSet.setFlag("1");
        exportSet.setCreateTime(DateHelper.currentDateTime());
        exportSet.setUptTime(DateHelper.currentDateTime());
        //组装数据先向员工自助提交审批信息，根据结果决定是否保存数据
        EssQueryModel essQueryModel = getEssBean(user.getYuSid(), exportSet.getApplyInfo());
        EssResult essResult = essApproveService.essProcess(essQueryModel);
        if (essResult.getCode() != 0){
            return new Result(-1, "提交申请失败,理由:"+essResult.getMsg());
        }else{
            //如果成功，先保存申请信息，再保存配置信息
            ExportApplyInfo applyInfo = exportSet.getApplyInfo();
            applyInfo.setId(IDGenerator.gen())
                    .setApplyStatus(FieldHandler.AUDIT)
                    .setSendStatus(FieldHandler.ZERO)
                    .setCreateTime(DateHelper.currentDateTime())
                    .setUpdateTime(DateHelper.currentDateTime());
            applyInfoMapper.addApply(applyInfo);
            exportSet.setCcisApplyId(applyInfo.getId());
            exportSet.setCcisReqNo(essResult.getRequestid());
            customersMapper.addExportSet(exportSet);
            return new Result(0, "提交申请成功！");
        }
    }

    private EssQueryModel getEssBean(String yuaId,ExportApplyInfo applyInfo){
        return EssQueryModel.of().setYuaId(yuaId)
                .setTqpc("0")
                .setLxdh(applyInfo.getPhone())
                .setYxdz(applyInfo.getEmail())
                .setJjcd(applyInfo.getDegree())
                .setXqlx(applyInfo.getReqType())
                .setXqbt(applyInfo.getReqTitle())
                .setXqbj(applyInfo.getReqBack())
                .setJgsczd(applyInfo.getReqWords())
                .setSqbmfzr(applyInfo.getDeptUserId())
                .setSqbmzgzjl(applyInfo.getManagerId())
                .setSfhmgxx(applyInfo.getIsSensitive())
                .setSjhdcyt(applyInfo.getUseTo())
                .setSjygts(applyInfo.getDataNum()+"")
                .setXykhhxxtdcmgxxdbyx(applyInfo.getIsNecessity());
    }
    /**
     * 导出客群审批通过
     *
     * @param customerId
     */
    @Override
    public void addPass(String customerId, String instanceId, String applicant) {

        Instance pass = approverService.pass(instanceId);
        Map<String, String> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("applicant", applicant);
        map.put("instanceId", pass.getId());
        ExportSet set = customersMapper.findCustomerSet(map);
        if (set != null) {
            User user = TagSecurityHelper.currentUser();
            Map<String, String> newMap = new HashMap<>();
            newMap.put("approveId", user.getUserId());
            newMap.put("approveName", user.getName());
            newMap.put("uptTime", DateHelper.currentDateTime());
            newMap.put("id",set.getId());

            FileLoadMqMsg fileLoadMqMsg = new FileLoadMqMsg();
            fileLoadMqMsg.setId(set.getId());
            fileLoadMqMsg.setUniqueIdentify(set.getId()+"_"+ RandomUtil.randomString(5));
            try {
                String msg = objectMapper.writeValueAsString(fileLoadMqMsg);
                rocketMQTemplate.convertAndSend(MQConfig.FILE_LOAD_TAG_TOPIC, msg);
                //推送成功
                newMap.put("isready", "1");
            } catch (JsonProcessingException e) {
                log.error("客群导出信息推送MQ失败"+e);
                newMap.put("isready", "3");
                newMap.put("reason","客群导出信息推送MQ失败"+e.getMessage());
            }
            customersMapper.updateById(newMap);

        }
    }

    /**
     * 审批驳回
     *
     * @param customerId
     */
    @Override
    public void reject(String customerId, String applicant, String instanceId, String desc) {
        //Instance instance = findInstance(customersId);
        Instance reject = approverService.reject(instanceId, desc);
        Map<String, String> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("applicant", applicant);
        map.put("instanceId", instanceId);
        User user = TagSecurityHelper.currentUser();
        map.put("approveId", user.getUserId());
        map.put("approveName", user.getName());
        customersMapper.updateReadyFile(map);
    }

    /**
     * 获取审批列表
     *
     * @param pageNumber
     * @param pageSize
     * @param customerName
     * @param approveType
     * @param approveState
     * @param uptTimeStart
     * @param uptTimeEnd
     */
    @Override
    public CustomersPage<ExportSet> findList(Integer pageNumber, Integer pageSize, String customerName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        //获取权限id
        List<String> workflowIds = findInstanceByPower(approveType);
        if (CollectionUtils.isEmpty(workflowIds)) {
            workflowIds.add(IDGenerator.gen());
        }
        Map map = new HashMap();
        map.put("customerName", customerName);
        map.put("approveState", approveState);
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        map.put("workflowIds", workflowIds);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<ExportSet> list = customersMapper.findCusApproveList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            for (ExportSet exportSet : list) {
                if (temp.compareTo(exportSet.getUptTime()) < 1) {
                    exportSet.setIsnew(true);
                } else {
                    exportSet.setIsnew(false);
                }
            }
        }
        CustomersPage<ExportSet> customersPage = new CustomersPage<>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(pageNumber);
        return customersPage;
    }

    /**
     * 获取所有的申请类型
     */
    @Override
    public Map findApproveType() {
        Map map = new HashMap();
        map.put(TagConstants.Workflow.ID_10008, Permissions.of(TagConstants.Workflow.ID_10008)
                                                           .getName());
        map.put(TagConstants.Workflow.ID_10009, Permissions.of(TagConstants.Workflow.ID_10009)
                                                           .getName());
        map.put(TagConstants.Workflow.ID_10010, Permissions.of(TagConstants.Workflow.ID_10010)
                                                           .getName());
        map.put(TagConstants.Workflow.ID_10016, Permissions.of(TagConstants.Workflow.ID_10016)
                .getName());
        return map;
    }

    @Override
    public Customers findApprovalOne(String workflowId, String customersId) {
        Map<String, String> map = new HashMap<>();
        map.put("workflowId", workflowId);
        map.put("customersId", customersId);
        User user = TagSecurityHelper.currentUser();
        map.put("userId", user.getUserId());
        return customersMapper.findCusApproveOne(map);
    }

    @Override
    public void addExportSet(ExportSet exportSet) {
        if (StringUtils.isEmpty(exportSet.getId())) {
            exportSet.setId(IDGenerator.gen());
        }
        customersMapper.addExportSet(exportSet);
    }

    @Override
    public void download(String id, HttpServletResponse response, HttpServletRequest request) {
        ExportSet exportSet = customersMapper.findById(id);
        if (exportSet != null) {
            ByteArrayInputStream bis = null;
            OutputStream os = null;
            byte[] data = null;
            try {
                response.setContentType("text/plain;charset=UTF-8");
                String fileName = exportSet.getExportName() + "_" + exportSet.getDataDate() + "_" + exportSet.getFileDate();
                boolean flag = request.getHeader("User-Agent")
                                      .indexOf("like Gecko") > 0;
                if (request.getHeader("User-Agent")
                           .toLowerCase()
                           .indexOf("msie") > 0 || flag) {
                    fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
                } else {
                    fileName = new String(fileName.replaceAll(" ", "")
                                                  .getBytes(StandardCharsets.UTF_8), "ISO8859-1");
                }
                response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".txt");
                //data = InputStream2ByteArray(exportSet.getExportAddress());
                //bis = new ByteArrayInputStream(data);
                //int i = bis.available();
                //byte[] bytes = new byte[i];
                //bis.read(bytes);
                //os = response.getOutputStream();
                //os.write(bytes);
                //os.flush();
                data = InputStream2ByteArray(exportSet.getExportAddress());
                bis = new ByteArrayInputStream(data);
                os = response.getOutputStream();
                byte[] buffer = new byte[2048];
                int n = 0;
                while ((n = bis.read(buffer)) != -1) {
                    os.write(buffer, 0, n);
                }
                os.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    @Override
    public Result pushFile(String id) {
        ExportSet exportSet = customersMapper.findById(id);
        ExportApplyInfo apply=applyInfoMapper.findApply(exportSet.getCcisApplyId());
        if (apply == null){
            return new Result(-1,"未找到对应申请信息!");
        }
        //如果是初始状态
        OcdsmModel ocdsmModel = new OcdsmModel();
        ocdsmModel.setFilePath(exportSet.getExportAddress());
        ResultObject resultObject;
        if (!Objects.equals(apply.getSendStatus(),"100420")){
            //组装条件
            resultObject=ocdsmService.sendFile(ocdsmModel);
            if(!Objects.equals(resultObject.getResult(),"100420")){
                return new Result(-1,"文件推送数据保险箱失败(状态码:"+resultObject.getResult()+")");
            }else{
                Map<String,String>params =new HashMap<>();
                params .put("zipName",resultObject.getZipFilePath());
                params.put("sendStatus",resultObject.getResult( ));
                params.put("id",apply.getId());
                applyInfoMapper.updateApply(params);
                //保存下载的记录,这里为什么不走1og工程下的DownloadLogsInterceptor:这里的下载可以无限点击，并不都是触发下载动作
                User user = SecurityHelper.currentUser();
                OcdsmDownLog ocdsmDownLog = new OcdsmDownLog().setId(IDGenerator.gen()).setParam(id).setUserId(user.getUserId()).setCreateTime(new Date());
                applyInfoMapper.saveDownLog(ocdsmDownLog);
                return new Result(0,"文件正在推送数据保险箱,请稍后前往查阅(状态码:"+resultObject.getResult()+")");}
        }else{
            return new Result(0,"文件已成功推送到数据保险箱,无需重复推送(状态码:"+apply.getSendStatus()+")");
        }
    }


    @Override
    public ExportSet findCustomerSet(String customerId, String instanceId, String applicant) {
        Map<String, String> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("applicant", applicant);
        map.put("instanceId", instanceId);
        ExportSet set = customersMapper.findCustomerSet(map);
        if (set != null && !StringUtils.isEmpty(set.getFieldValue())) {
            //处理部分字段，方便前端回显
            Map<String, String> valueMap = new HashMap<>();
            String[] values = set.getFieldValue()
                                 .split(",");
            for (String dimId : values) {
                valueMap.put(dimId, customersMapper.findNameByDimId(dimId));
            }
            set.setMap(valueMap);
        }
        return set;
    }

    @Override
    public ExportSet findExportById(String id) {

        ExportSet set = customersMapper.findExportById(id);
        if (!Objects.isNull(set)){
            if (StrUtil.isNotBlank(set.getFieldValue())){
                //处理部分字段，方便前端回显
                Map<String, String> valueMap = new HashMap<>();
                String[] values = set.getFieldValue()
                        .split(",");
                for (String dimId : values) {
                    valueMap.put(dimId, customersMapper.findNameByDimId(dimId));
                }
                set.setMap(valueMap);
            }
            if (StrUtil.isNotBlank(set.getCcisApplyId())){
                ExportApplyInfo apply = applyInfoMapper.findApply(set.getCcisApplyId());
                set.setApplyInfo(apply);
            }
        }
        return set;
    }

    @Override
    public boolean checkExportSet(ExportSet paramSet) {
        Map<String, String> map = new HashMap<>();
        map.put("customerId", paramSet.getCustomerId());
        User user = TagSecurityHelper.currentUser();
        map.put("applicant", user.getUserId());
        List<ExportSet> esList = customersMapper.findNewData(map);
        if (CollectionUtils.isEmpty(esList)) {
            return false;
        }
        for (ExportSet ex : esList) {
            if (!checkUpdate(paramSet, ex)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean checkExportSetting(ExportSet paramSet) {
        if(StrUtil.isNotBlank(paramSet.getExportName())){
            int count = customersMapper.checkExportName(paramSet.getExportName());
            if(count<=0){
                return true;
            }
        }
        return false;
    }

    @Override
    public CustomersPage<ExportSet> findRecordList(Integer pageNumber, Integer pageSize,String customerId, String customerName, String approveState, String exportName, String isready) {
        Map map = new HashMap();
        map.put("customerId", customerId);
        map.put("customerName", customerName);
        map.put("exportName", exportName);
        map.put("approveState", approveState);
        map.put("isready", isready);
        User user = SecurityHelper.currentUser();
        map.put("userId", user.getUserId());
        List<String> workflowIds = new ArrayList<>();
        workflowIds.add(TagConstants.Workflow.ID_10008);
        map.put("workflowIds", workflowIds);
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<ExportSet> list = customersMapper.findRecordList(map);
        CustomersPage<ExportSet> result = new CustomersPage<>();
        //对datadate做回显处理
        for(ExportSet e:list){
            if(!(FieldHandler.pattern.matcher(e.getDataDate()).matches() && e.getDataDate().length() == FieldHandler.LENGTH8)){
                String finalDate = customersMapper.findTime(e.getIndexId(),e.getDataDate());
                e.setDataDate(finalDate);
            }
            if (StrUtil.isNotBlank(e.getCcisApplyId())){
                ExportApplyInfo apply = applyInfoMapper.findApply(e.getCcisApplyId());
                e.setApplyInfo(apply);
            }
        }
        result.setContent(list);
        result.setTotalPages(page.getPages());
        result.setTotalElements(page.getTotal());
        result.setSize(page.getPageSize());
        result.setRequestPager(pageNumber);
        return result;
    }

    @Override
    public boolean retry(String id) {
        boolean flag = false;
        Map<String,String> map = new HashMap();
        map.put("uptTime", DateHelper.currentDateTime());
        map.put("id",id);
        //客群导出推送消息
        FileLoadMqMsg fileLoadMqMsg = new FileLoadMqMsg();
        fileLoadMqMsg.setId(id);
        fileLoadMqMsg.setUniqueIdentify(id+"_"+RandomUtil.randomString(5));
        try {
            String msg = objectMapper.writeValueAsString(fileLoadMqMsg);
            rocketMQTemplate.convertAndSend(MQConfig.FILE_LOAD_TAG_TOPIC, msg);
            //推送成功
            map.put("isready", "1");
            map.put("reason","-");
            flag = true;
        } catch (JsonProcessingException e) {
            log.error("客群导出信息推送MQ失败"+e);
            map.put("isready", "3");
            map.put("reason","客群导出信息推送MQ失败"+e.getMessage());
        }
        customersMapper.updateById(map);
        return flag;
    }

    @Override
    public void test(String id, String isReady, String reason) {
        Map<String,String> map = new HashMap();
        map.put("uptTime", DateHelper.currentDateTime());
        map.put("id",id);
        map.put("isready", isReady);
        map.put("reason",reason);
        customersMapper.updateById(map);
    }

    @Override
    public void updateApply(String id, String sendStatus, String zipName) {
        Map<String,String> map = new HashMap();
        map.put("id",id);
        map.put("sendStatus",sendStatus);
        map.put("zipName",zipName);
        applyInfoMapper.updateApply(map);
    }

    boolean checkUpdate(ExportSet paramSet, ExportSet dbSet) {
        boolean flag = false;
        //判断导出字段是否变动
        if (!paramSet.getExportField()
                     .equals(dbSet.getExportField())) {
            flag = true;
        } else if ("1".equals(dbSet.getExportField())) { //如果都是部分字段导出比较每一项的值时候变动
            flag = checkString(dbSet.getFieldValue(), paramSet.getFieldValue());
        }
        //判断导出类型是否变动
        if (!paramSet.getExportType()
                     .equals(dbSet.getExportType())) {
            flag = true;
        }
        return flag;
    }

    @Override
    public void exportFlush(ExportSet exportSet) {
        //先调提交审批
        exportSet.setFlag("1");
        String instanceId = addCommit(exportSet.getCustomerId(), exportSet);
        User user = SecurityHelper.currentUser();
        //再调审批通过
        addPass(exportSet.getCustomerId(), instanceId, user.getUserId());
    }

    private boolean checkString(String dbstr, String parmstr) {
        boolean flag = false;
        Set<String> dbSet1 = new HashSet(Arrays.asList(dbstr.split(",")));
        Set<String> parmSet1 = new HashSet(Arrays.asList(parmstr.split(",")));
        if (dbSet1.size() != parmSet1.size()) {
            flag = true;
        } else {
            for (String str : dbSet1) {
                if (!parmSet1.contains(str)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    private byte[] InputStream2ByteArray(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();
        return data;
    }

    private byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }

    /**
     * 获取流程实例对象
     *
     * @param dimId
     * @return
     */
    public Instance findInstance(String dimId) {
        Map<String, Instance> map = submitterService.fetchByResources(new SubmitterService.FetchByResourcesParam().addResourceId(dimId)
                                                                                                                  .setContainsDeleted(false)
                                                                                                                  .setCurrentStatus(Status.WAITTING.code()));
        Set<Map.Entry<String, Instance>> entries = map.entrySet();
        for (Map.Entry<String, Instance> e : entries) {
            String resource = e.getValue()
                               .getResource();
            System.out.println("测试打印================1" + resource);
            System.out.println("测试打印================2" + e.getValue()
                                                          .getId());
        }
        Instance instance = map.get(dimId);
        return instance;
    }

    /**
     * 获取用户有权审批的流程实例
     *
     * @return
     */
    public List<String> findInstanceByPower(String workflowId) {
        List<String> workflowIds = new ArrayList<>();
        if (StringUtils.isEmpty(workflowId)) {
            for (String workflowDefinitionId : TagConstants.Workflow.values()) {
                if (SecurityHelper.containsPermission(workflowDefinitionId)) {
                    workflowIds.add(workflowDefinitionId);
                }
            }
        } else {
            if (!SecurityHelper.containsPermission(workflowId)) {
                User user = SecurityHelper.currentUser();
                throw new WorkflowException((ExceptionCodes.WORKFLOW_20006.args(user.getUserId(), workflowId)));
            }
            workflowIds.add(workflowId);
        }
        return workflowIds;
    }

    @Override
    public void handleCCISMessage(String message) {
        log.info("接收CCIS员工自助系统通知：{}",message);
        CCISQueryModel ccisQueryModel = JSONObject.parseObject(message, CCISQueryModel.class);
        //根据流水号找到对应的记录数据
        ExportSet ex = customersMapper.findByReqNo(ccisQueryModel.getReqNo());
        if (ex != null){
            if (ccisQueryModel.isApproveResult()){

                Map<String, String> newMap = new HashMap<>();
                newMap.put("id", ex.getCcisApplyId());
                newMap.put("applyStatus", FieldHandler.PASS);
                //为了防止审批那边重复推送数据过来，将sendStatus字段置为初始状态
                newMap.put("sendStatus",FieldHandler.ZERO);
                newMap.put("updateTime",  DateHelper.currentDateTime());
                applyInfoMapper.updateApply(newMap);

                newMap.put("id",ex.getId());
                newMap.put("approveId", ccisQueryModel.getApproveId());
                newMap.put("approveName", ccisQueryModel.getApproveName());
                newMap.put("uptTime", DateHelper.currentDateTime());

                FileLoadMqMsg fileLoadMqMsg = new FileLoadMqMsg();
                fileLoadMqMsg.setId(ex.getId());
                fileLoadMqMsg.setUniqueIdentify(ex.getId()+"_"+RandomUtil.randomString(5));
                try {
                    String msg = objectMapper.writeValueAsString(fileLoadMqMsg);
                    rocketMQTemplate.convertAndSend(MQConfig.FILE_LOAD_TAG_TOPIC, msg);
                    //推送成功
                    newMap.put("isready", "1");
                } catch (JsonProcessingException e) {
                    log.error("客群导出信息推送MQ失败"+e);
                    newMap.put("isready", "3");
                    newMap.put("reason","客群导出信息推送MQ失败"+e.getMessage());
                }
                customersMapper.updateById(newMap);
            }else{
                Map<String, String> map = new HashMap<>();
                map.put("id",ex.getCcisApplyId());
                map.put("applyStatus", FieldHandler.REJECT);
                map.put("updateTime",  DateHelper.currentDateTime());
                applyInfoMapper.updateApply(map);

                map.put("id",ex.getId());
                map.put("approveId", ccisQueryModel.getApproveId());
                map.put("approveName", ccisQueryModel.getApproveName());
                map.put("reason","拒绝理由："+ccisQueryModel.getReason());
                map.put("uptTime", DateHelper.currentDateTime());
                customersMapper.updateById(map);
            }
        }

    }

    private static String format(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return sdf.format(date);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public void releaseCommit(String customersId) {
        Instance submit = submitterService.submit(new SubmitterService.SubmitParam().setResourceId(customersId)
                .setWorkflowId(TagConstants.Workflow.ID_10009));
        Customers customers = new Customers();
        customers.setApprovalStatus("2");
        customers.setCustomersId(customersId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        customers.setApplicationTime(sdf.format(new Date()));
        customers.setUptTime(sdf.format(new Date()));
        User user = TagSecurityHelper.currentUser();
        customers.setApplicant(user.getUserId());
        customers.setApplicantName(user.getName());
        customersMapper.updateCustomers(customers);
        if(SecurityHelper.containsPermission(Permissions.WORKFLOW_DEFINITION_10014.getCode())){
            try{
                this.releasePass(customersId, submit.getId());
            }catch(QuickException e){
                log.error(e.getMessage());
            }catch(Exception e){
                log.error("自动审核 客群发布 通过 出错", e);
            }
        }
    }
   //审核通过后，对静态客群进行标记
   private void doMark(String customersId){
       Customers customers = customersMapper.findOneById(customersId);
       if(PublicConstant.TRUE.equals(customers.getDateType())){
           //向MQ发送打标记的消息
           StaticMqMsg dynamicStaticMqMsg = new StaticMqMsg(customersId,customersMapper.findFlag(),customersId+"_"+ RandomUtil.randomString(6));
           try {
               String msg = objectMapper.writeValueAsString(dynamicStaticMqMsg);
               rocketMQTemplate.convertAndSend(MQConfig.STATIC_CUSTOMERS_TOPIC, msg);
           } catch (JsonProcessingException e) {
               throw new RuntimeException(e);
           }catch(Exception e){
               throw QuickException.normal(ERROR_401006.args(customersId));
           }
       }
   }

    @Override
    public void releasePass(String customersId, String instanceId) {
        Instance pass = approverService.pass(instanceId);
        Customers customers = new Customers();
        customers.setApprovalStatus("4");
        customers.setCustomersId(customersId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        customers.setUptTime(sdf.format(new Date()));
        User user = TagSecurityHelper.currentUser();
        customers.setApprover(user.getUserId());
        customers.setApproverName(user.getName());
        updateAmount(customers);
        customersMapper.updateCustomers(customers);
        doMark(customersId);
    }

    private void updateAmount(Customers customers) {
        try{
            Customers info = customersService.findOneById(customers.getCustomersId());
            //如果是静态客群true不走更新客数操作，因为他是固定不变的，在保存客群的时候就现查保存了
            if (FieldHandler.FALSE.equals(info.getDateType())){
                customers.setIndexId(info.getIndexId());
                customers.setDateType(info.getDateType());
                customersService.getCountAmount(customers, info.getQueryModel());
            }
        }catch (Exception e){
            log.error("获取客群人数出错", e);
        }
    }

    @Override
    public void releasereject(String customersId, String instanceId, String desc) {
        //Instance instance = findInstance(dimId);
        Instance reject = approverService.reject(instanceId, desc);
        Customers customers = new Customers();
        customers.setApprovalStatus("3");
        customers.setCustomersId(customersId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        customers.setUptTime(sdf.format(new Date()));
        User user = TagSecurityHelper.currentUser();
        customers.setApprover(user.getUserId());
        customers.setApproverName(user.getName());
        customers.setRejectDesc(desc);//驳回意见
        customersMapper.updateCustomers(customers);
    }

    @Override
    public void releaseResubmit(String customersId) {
        Map<String, String> map = new HashMap<>();
        User user = TagSecurityHelper.currentUser();
        map.put("userId", user.getUserId());
        map.put("resourceId", customersId);
        map.put("workflowId", TagConstants.Workflow.ID_10009);
        Instance instance = instanceMapper.findInstance(map);
        Instance submit = submitterService.submit(new SubmitterService.SubmitParam().setInstanceId(instance.getId())
                                                                                    .setResourceId(customersId)
                                                                                    .setWorkflowId(instance.getWorkflowId()));
        Customers customers = new Customers();
        customers.setApprovalStatus("2");
        customers.setCustomersId(customersId);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        customers.setApplicationTime(sdf.format(new Date()));
        customers.setUptTime(sdf.format(new Date()));
        customers.setApplicant(user.getUserId());
        customers.setApplicantName(user.getName());
        customers.setRejectDesc("-");
        customersMapper.updateCustomers(customers);
        if(SecurityHelper.containsPermission(Permissions.WORKFLOW_DEFINITION_10014.getCode())){
            try{
                this.releasePass(customersId, submit.getId());
            }catch(QuickException e){
                log.error(e.getMessage());
            }catch(Exception e){
                log.error("自动审核 客群发布 通过 出错", e);
            }
        }
    }

    @Override
    public CustomersPage<Customers> findReleaseList(Integer pageNumber, Integer pageSize, String customersName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        //获取权限id
        List<String> workflowIds = findInstanceByPower(approveType);
        if (CollectionUtils.isEmpty(workflowIds)) {
            workflowIds.add(IDGenerator.gen());
        }
        Map map = new HashMap();
        map.put("customersName", customersName);
        map.put("approveState", approveState);
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        map.put("workflowIds", workflowIds);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<Customers> list = customersMapper.findReleaseApproveList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Customers customers : list) {
                if (temp.compareTo(customers.getUptTime()) < 1) {
                    customers.setIsnew(true);
                } else {
                    customers.setIsnew(false);
                }
            }
        }
        CustomersPage<Customers> customersPage = new CustomersPage<Customers>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(pageNumber);
        return customersPage;
    }

    @Override
    public void deleteCommit(String customersId) {
        Customers customers = customersMapper.findOneById(customersId);
        if (customers != null) {
            Instance instance = submitterService.submit(new SubmitterService.SubmitParam().setResourceId(customersId)
                                                                                          .setWorkflowId(TagConstants.Workflow.ID_10010));
            CustomersApprovalRecord record = new CustomersApprovalRecord();
            record.setId(IDGenerator.gen());
            record.setCustomersId(customersId);
            record.setCustomersName(customers.getCustomersName());
            record.setCustomersDes(customers.getCustomersDes());
            record.setWorkflowId(TagConstants.Workflow.ID_10010);
            record.setInstanceId(instance.getId());
            User user = TagSecurityHelper.currentUser();
            record.setOwerId(user.getUserId());
            record.setOwerName(user.getName());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            record.setApplicantTime(sdf.format(new Date()));
            record.setUptTime(sdf.format(new Date()));
            record.setApproverStatus("2");
            recordMapper.addRecord(record);
            if(SecurityHelper.containsPermission(Permissions.WORKFLOW_DEFINITION_10015.getCode())){
                try{
                    this.deletePass(customersId, instance.getId());
                }catch (Exception e){
                    log.error("自动审核 客群发布 通过 出错", e);
                }
            }
        }
    }

    @Override
    public void deletePass(String customersId, String instanceId) {
        Instance pass = approverService.pass(instanceId);
        Map map = new HashMap();
        map.put("approverStatus", "4");
        User user = TagSecurityHelper.currentUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("approver", user.getUserId());
        map.put("approverName", user.getName());
        map.put("approverTime", sdf.format(new Date()));
        map.put("uptTime", sdf.format(new Date()));
        map.put("workflowId", TagConstants.Workflow.ID_10010);
        map.put("customersId", customersId);
        map.put("instanceId", instanceId);
        recordMapper.updateRecord(map);
        //删除客群相关信息
        customersService.delCustomers(customersId);
    }

    @Override
    public void deleteReject(String customersId, String instanceId, String desc) {
        Instance reject = approverService.reject(instanceId, desc);
        Map map = new HashMap();
        map.put("approverStatus", "3");
        User user = TagSecurityHelper.currentUser();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("approver", user.getUserId());
        map.put("approverName", user.getName());
        map.put("approverTime", sdf.format(new Date()));
        map.put("uptTime", sdf.format(new Date()));
        map.put("workflowId", TagConstants.Workflow.ID_10010);
        map.put("customersId", customersId);
        map.put("instanceId", instanceId);
        map.put("rejectDes", desc);
        recordMapper.updateRecord(map);
    }

    @Override
    public void deleteResubmit(String customersId) {
        Map<String, String> map = new HashMap<>();
        User user = TagSecurityHelper.currentUser();
        map.put("userId", user.getUserId());
        map.put("resourceId", customersId);
        map.put("workflowId", TagConstants.Workflow.ID_10010);
        Instance instance = instanceMapper.findInstance(map);
        Instance submit = submitterService.submit(new SubmitterService.SubmitParam().setInstanceId(instance.getId())
                                                                                    .setResourceId(customersId)
                                                                                    .setWorkflowId(instance.getWorkflowId()));
        map.put("approverStatus", "2");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("owerId", user.getUserId());
        map.put("owerName", user.getName());
        map.put("applicantTime", sdf.format(new Date()));
        map.put("uptTime", sdf.format(new Date()));
        map.put("customersId", customersId);
        map.put("instanceId", instance.getId());
        map.put("rejectDes", "-");
        recordMapper.updateRecord(map);
    }

    @Override
    public CustomersPage<CustomersApprovalRecord> findDelRecordList(Integer pageNumber, Integer pageSize, String customersName, String approveType, String approveState, String uptTimeStart, String uptTimeEnd) {
        //获取权限id
        List<String> workflowIds = findInstanceByPower(approveType);
        if (CollectionUtils.isEmpty(workflowIds)) {
            workflowIds.add(IDGenerator.gen());
        }
        Map map = new HashMap();
        map.put("customersName", customersName);
        map.put("approverStatus", approveState);
        map.put("uptTimeStart", uptTimeStart);
        if (uptTimeEnd != null && !"".equals(uptTimeEnd)) {
            map.put("uptTimeEnd", uptTimeEnd + "23.59.59");
        }
        map.put("workflowIds", workflowIds);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(calendar.MONTH, -2);
        String temp = format(calendar.getTime());
        Page page = PageHelper.startPage(pageNumber, pageSize);
        List<CustomersApprovalRecord> list = recordMapper.findDelApproveList(map);
        if (CollectionUtils.isNotEmpty(list)) {
            for (CustomersApprovalRecord record : list) {
                if (temp.compareTo(record.getUptTime()) < 1) {
                    record.setIsnew(true);
                } else {
                    record.setIsnew(false);
                }
            }
        }
        CustomersPage<CustomersApprovalRecord> customersPage = new CustomersPage<CustomersApprovalRecord>();
        customersPage.setContent(list);
        customersPage.setTotalPages(page.getPages());
        customersPage.setTotalElements(page.getTotal());
        customersPage.setSize(page.getPageSize());
        customersPage.setRequestPager(pageNumber);
        return customersPage;
    }

    @Override
    public String findDelById(String customersId, String workflowId) {
        Map map = new HashMap();
        map.put("customersId", customersId);
        map.put("workflowId", TagConstants.Workflow.ID_10010);
        CustomersApprovalRecord record = recordMapper.findDelById(map);
        if (record == null) {
            return "1";//未提交
        } else {
            return record.getApproverStatus();
        }
    }
}
